#-*- coding: utf-8 -*-
#! /usr/bin/python

import sys
import ConfigParser
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import httplib
import re
import base64
import time

reload(sys)
sys.setdefaultencoding("utf-8")


def lgRouter():
    # 192.168.1.1
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
        "Connection": "keep-alive"}

    # get status page
    conn.request("GET", "/userRpm/StatusRpm.htm", "", headers)
    response = conn.getresponse()
    keyword = re.search(' wanPara [^\)]*?\)', response.read())
    response.close()
    conn.close()

    # search the public ip address
    found = 0
    publicIP = ""
    if keyword:
        arr = re.findall('([\d]*?,)|(\"[^\"]*?\",)', keyword.group(0))
        if arr:
            if len(arr) > 3:
                publicIP = re.search('(?<=\")[^\"]*?(?=\")', arr[2][1])
                if publicIP:
                    publicIP = publicIP.group(0)
                    found = 1

    if found == 1:
        return publicIP
    else:
        return "Error"


def diconectRouter():
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
        "Connection": "keep-alive"}  

    sparam = "?Disconnect=%B6%CF%20%CF%DF&wan=1"    
    conn.request("GET", "/userRpm/StatusRpm.htm"+sparam, "", headers)    
    response = conn.getresponse()
    keyword = re.search(' wanPara [^\)]*?\)', response.read())
    response.close()
    conn.close()
    
    # search the public ip address
    found = 0
    publicIP = ""
    if keyword:
        arr = re.findall('([\d]*?,)|(\"[^\"]*?\",)', keyword.group(0))
        if arr:
            if len(arr) > 3:
                publicIP = re.search('(?<=\")[^\"]*?(?=\")', arr[2][1])
                if publicIP:
                    publicIP = publicIP.group(0)
                    found = 1
    if(publicIP == '0.0.0.0'):
        #print "disconect!"
        return True
    else:
        #print publicIP
        return False


def connectRouter():
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.9,*;q=0.8",
        "Referer": "http://192.168.1.1/userRpm/StatusRpm.htm",
        "Host": "192.168.1.1",
        "Connection": "keep-alive"}  

    sparam = "?Connect=%C1%AC%20%BD%D3&wan=1"    
    conn.request("GET", "/userRpm/StatusRpm.htm"+sparam, "", headers)
    conn.close()
    time.sleep(0.9)
    rt = lgRouter()

    if(rt=="0.0.0.0"):
        print "Status is disconect"        
    else:
        if(rt=="Error"):
            print "Status is Error"
        else:
            print "Status is conect,ip is "+rt
    return rt

def changeip():
    rt = lgRouter()
    if(rt=="0.0.0.0"):
        print "Status is disconect"
    else:
        if(rt=="Error"):
            print "Status is Error"
        else:
            print "Status is conect,ip is "+rt
    rt = diconectRouter()
    if(rt):
        print "Disconect the Router Successfully"
    time.sleep(0.5)
    rtt = connectRouter()
    i =  5
    while((rtt == rt) and (i>0)):
        diconectRouter()
        rtt = connectRouter()
        i = i - 1

def logoutTb():
    '''
    logout from taobao
    '''
    lurl = "http://login.taobao.com/member/logout.jhtml?spm=a1z02.1.0.6.wXTWrc&amp;f=top&amp;out=true&amp;redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fnekot%3Ds6S6%252BtfTtcTQodHy1351908154890"
    chrome.get(lurl)

def loginTb(username,password):
    '''
    jhfnetboy@gmail.com create to login taobao
    '''
    #chrome.delete_all_cookies()
    lgurl = 'https://login.taobao.com/member/login.jhtml'
    chrome.get(lgurl)
    #set username and password
    try:
        chrome.find_element_by_class_name('nickx').click()
    except:
        pass
    try:
        #chrome.execute_script("document.getElementByName('TPL_username').value = '11'")
        uname = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("TPL_username"))
        uname.send_keys(username.decode('utf-8'))
    except:
        print 'fail to get element TPL_username'
    try:
        ckbox = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_SafeLoginCheck"))
        ckbox.click()
    except:
        print 'fail to get element J_SafeLoginCheck'
    try:
        pword = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("TPL_password"))
        pword.send_keys(password)
    except:
        print 'fail to get element TPL_password'
    try:
        btn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_SubmitStatic"))
        btn.click()
    except:
        print 'fail to get element J_SubmitStatic'
    try:
        lgok = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_link_text(username.decode('utf-8')))
        return True
    except:
        return False


def initConfig(filename):
    '''
    去掉文件头BOM等
    Window下用记事本打开配置文件并修改保存后，编码为UNICODE
    或UTF-8的文件的文件头
    #会被相应的加上\xff\xfe（\xff\xfe）或\xef\xbb\xbf
    '''
    import re
    content = open(filename).read()
    content = re.sub(r"\xfe\xff", "", content)
    content = re.sub(r"\xff\xfe", "", content)
    content = re.sub(r"\xef\xbb\xbf", "", content)
    open(filename, 'w').write(content)


def logit(content, filename='log.txt'):
    '''
    逐行添加日志，每行一个回车
    头部是时间
    '''
    file = open(filename, 'a')
    try:
        file.write('\r\n'+content+'\r\n')
    finally:
        file.close()


def pai(item, count):
    '''
    buy url item
    '''
    time.sleep(0.9)
    chrome.stop_client()
    chrome.get(item)
    time.sleep(1.5)
    chrome.switch_to_frame("J_BundleDetail")
    chrome.stop_client()  
    try:#submit form，在产品页面，点击购买
        fm = chrome.find_element_by_id('J_FrmBid')
        fm.submit()
    except:
        print 'fail to get element J_FrmBid'
    time.sleep(1.1)
    try:#submit order #anoymous进入购买确认页面，匿名
        chrome.stop_client()
        anonybox = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("anony"))
        anonybox.click()
        chrome.execute_script("document.getElementById('anony').checked = true ")
    except:
        print 'fail to get element anony'
    time.sleep(0.9)
    try:#pay-for-another，代付款
        chrome.execute_script("document.getElementById('pay-for-another').checked = true")
    except:
        print 'fail to get element pay-for-another'
    try:#set count，设置数量
        cnt = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("quantityInput"))
        cnt.click()
        chrome.execute_script("document.getElementById('quantityInput').value = "+count)
    except:
        print 'fail to get element quantityInput'
    time.sleep(1.2)
    try:#submit，确认无误，购买
        sbt = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_OrderForm"))
        sbt.submit()
    except:
        print 'fail to get element performSubmit'
    try:#取消支付宝的新手导航
        chrome.execute_script("document.getElementById('J_guide_backgroundImg').style.display= 'none'")  
    except:
        print 'cancel alipay navigator failed'
    try:
        skip = chrome.find_element_by_name("skip")
        skip.click()
    except:
        print 'click skip fail'
    try:#click other-method-trigger  进入付款页面，点其他付款方式（代付链接）     
        anlink = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("other-method-trigger"))
        anlink.click()
    except:
        print 'fail to click other link'
    try:#click btn #name = orderId      
        anbtn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_elements_by_class_name("ui-button-text"))
        anbtn[1].submit()
    except:
        print 'fail to click produce otherpay link btn'
    try:#get link text
        time.sleep(1.1)
        txt = chrome.find_element_by_xpath("//input[@id='link-value']")
        linktxt = txt.get_attribute('value')
        logit(linktxt, 'linktxt.log')
        print txt.get_attribute('value')
    finally:
        pass

    
def mainfun():
    config = ConfigParser.ConfigParser()
    initConfig('fast.ini')
    config.read('fast.ini')
    xiaohaocount = int(config.get("global", "xiaohaocount"))
    item = config.get("global", "item")
    count = int(config.get("global", "count"))
    xiaohao = range(xiaohaocount)
    lpass = range(xiaohaocount)
    for i in range(xiaohaocount):
        xiaohao[i] = config.get("xiaohao", "hao"+str(i+1))    
        lpass[i] = config.get("lpass", "lpass"+str(i+1))    
        if(loginTb(xiaohao[i], lpass[i])):
            try:
                #print 'sure it'+xiaohao[i]+'::'+lpass[i]
                #logoutTb()
                changeip()
                pai(item, count)
                #退出支付宝
                alout = chrome.find_element_by_link_text('退出'.decode('utf-8'))
                alout.click()
                #chrome.get('https://auth.alipay.com/login/logout.htm')                
                chrome.delete_all_cookies()
            except:
                print 'pai Error!!'



chrome = webdriver.Ie()
#chrome = webdriver.Chrome()
mainfun()
chrome.close()

